//
//  SchoolView.m
//  Comma
//
//  Created by 杜远洋 on 15-1-20.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SchoolView.h"
#import "GlobalMacro.h"
#import "GlobalMethod.h"
#import "SchoolTableViewCell.h"
#import "URLMacro.h"
#import "AFNetworking.h"
#import "SchoolModel.h"
#import "PinYinForObjc.h"
#import "ChineseInclude.h"
#import "LoadIndicator.h"
@implementation SchoolView
- (id)initWithLeftButton:(NSString *)leftTitle RightButton:(NSString *)rightTitle Title:(NSString *)title FooterView:(FooterViewState)footer
{
    self = [super initWithLeftButton:leftTitle RightButton:rightTitle Title:title FooterView:footer];
    if (self) {
        self.tableArray = [NSMutableArray array];
        self.schoolInfo = [NSMutableDictionary dictionary];
        self.schoolHeadInfo = [NSMutableDictionary dictionary];
    }
    return self;
}
- (void)createMySchoolName
{
    [self setBackgroundColor:[UIColor whiteColor]];
    [self getMyScHOOLData];
   
}
- (void)getMyScHOOLData
{
//    NSURL *url = [NSURL URLWithString:@"http://www.isu.so/schools.json"];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSString *html = operation.responseString;
//        NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
//        NSArray *myArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//        for (NSDictionary *dic in myArray) {
//            SchoolModel *model = [[SchoolModel alloc] init];
//            [model setValuesForKeysWithDictionary:dic];
//            [self.tableArray addObject:model];
//        }
//        [self getPinYinSchool];
//        [self createMySchoolTable];
//        [self getMySchoolName];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
//        [fondView setBackgroundColor:[UIColor whiteColor]];
//        [self addSubview:fondView];
//        [LoadIndicator networkStateNotReachableInView:fondView];
//    }];
//    // 加入队列
//    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//    [queue addOperation:operation];

    
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dic" ofType:@"plist"]];
    NSArray *keysArray = [dic allKeys];
    
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        for (int i = 0; i < [keysArray count]; i++) {
            
            NSString *chinese = [dic objectForKey:[keysArray objectAtIndex:i]];
            SchoolModel *model = [[SchoolModel alloc] init];
            model.name = chinese;
            //汉字
            [self.tableArray addObject:model];
            
            //全拼
            NSString *myKey = [NSString stringWithFormat:@"%d",i];
            [self.schoolInfo setObject:[keysArray objectAtIndex:i] forKey:myKey];
            
            //转化汉字首字符的拼音
            NSString *tempPinYinHeadStr = [PinYinForObjc chineseConvertToPinYinHead:chinese];
            [self.schoolHeadInfo setObject:tempPinYinHeadStr forKey:myKey];
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            
        });
        
        
    });
    [self createMySchoolTable];
    [self getMySchoolName];

    
}
//- (void)getPinYinSchool
//{
//    for (int i=0; i<self.tableArray.count; i++) {
//        
//        SchoolModel *model = [self.tableArray objectAtIndex:i];
//        NSString *myKey = [NSString stringWithFormat:@"%d",i];
//        
//        //转化汉字为拼音
//        NSString *tempPinYinStr = [PinYinForObjc chineseConvertToPinYin:model.name];
//        [self.schoolInfo setObject:tempPinYinStr forKey:myKey];
//        
//        //转化汉字首字符的拼音
//        NSString *tempPinYinHeadStr = [PinYinForObjc chineseConvertToPinYinHead:model.name];
//        NSLog(@"%@", tempPinYinHeadStr);
//        [self.schoolHeadInfo setObject:tempPinYinHeadStr forKey:myKey];
//    }
//
//
//}

- (void)getMySchoolName
{
    UIView *SchoolView = [[UIView alloc] initWithFrame:CGRectMake(16, 64, SCREEN_WIDTH, 44)];
    [SchoolView setBackgroundColor:[UIColor clearColor]];
    [self addSubview:SchoolView];

    self.mySchoolName = [[UITextField alloc] initWithFrame:CGRectMake(0, 12, SCREEN_WIDTH - 32, 20)];
    [self.mySchoolName setBackgroundColor:[UIColor clearColor]];
    [self.mySchoolName setPlaceholder:@"请输入大学名称"];
    [self.mySchoolName setFont:[UIFont systemFontOfSize:14]];
    self.mySchoolName.delegate = self;
    
#pragma mark - 监听textfield的文本输入：自己写一个方法用于实现监听时要做什么
    [self.mySchoolName addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
    [SchoolView addSubview:self.mySchoolName];
    [self schoolNameSeperateLine];
}


- (void)schoolNameSeperateLine
{
    [GlobalMethod drawLineWithStartPoint:CGPointMake(16, 108) EndPoint:CGPointMake(SCREEN_WIDTH, 108) inUIView:self];
}
- (void)createMySchoolTable
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(16, 108, SCREEN_WIDTH - 32, SCREEN_HEIGHT - 108) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView registerClass:[SchoolTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self addSubview:self.tableView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (self.searchResultArray.count != 0) {
       
        return [self.searchResultArray count];
    }
    else
    {
        return [self.tableArray count];
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SchoolTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    if (self.searchResultArray.count != 0) {
        SchoolModel *model = [self.searchResultArray objectAtIndex:indexPath.row];
        [cell.schoolName setText:model.name];
    }
    else
    {
        SchoolModel *model = [self.tableArray objectAtIndex:indexPath.row];
        [cell.schoolName setText:model.name];
        
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
#pragma mark - 这个地方 当我们用searchBar的时候  就给searchbar.text赋值
    if (self.searchResultArray.count != 0) {
        SchoolModel *model = [self.searchResultArray objectAtIndex:indexPath.row];
        [self.mySchoolName setText:model.name];
    }
    else
    {
        SchoolModel *model = [self.tableArray objectAtIndex:indexPath.row];
        [self.mySchoolName setText:model.name];
        
    }

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 22;
}


#pragma mark - ok
- (void)textFieldDidChanged:(id)sender
{

    

    UITextField *input = (UITextField *)sender;
    input.text = [input.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    self.searchResultArray = [[NSMutableArray alloc] init];
    //拼音（判断输入的是否是汉字，如果是拼音就走下面的方法）
    if (input.text.length>0&&![ChineseInclude isIncludeChineseInString:input.text]) {
        for (int i=0; i<_tableArray.count; i++) {
            NSString *myKey = [NSString stringWithFormat:@"%d",i];
            //  包括汉字（判断数据里是否包含这个输入的拼音，如何判断：如果我的数据都是汉字 先把汉字转化为拼音  然后 看我汉字拼音里是否包含输入的拼音）
            if ([ChineseInclude isIncludeChineseInString:[self.schoolInfo objectForKey:myKey]]) {
                //把汉字转化为拼音（第一次 把汉字转化成的拼音全部存储到字典中，第二次输入就从字典里区比较，然后添加的是汉字model）
                NSString *tempPinYinStr = [PinYinForObjc chineseConvertToPinYin:[self.schoolInfo objectForKey:myKey]];
                //搜索拼音里是否包含我输入的字符
                NSRange titleResult=[tempPinYinStr rangeOfString:input.text options:NSCaseInsensitiveSearch];
                //如果包含 就添加到数组里
                if (titleResult.length>0) {
                    SchoolModel *model = [self.tableArray objectAtIndex:i];
                    [_searchResultArray addObject:model];
                }
                //这里是每个汉字的首字符搜索  如：bd  百度
                //这个是包含汉字的首字符 原理同上
                NSString *tempPinYinHeadStr = [PinYinForObjc chineseConvertToPinYinHead:[self.schoolInfo objectForKey:myKey]];
                //判断我汉字的拼音里是否包含 每个汉字的首字符 如果是 就添加到数组里
                NSRange titleHeadResult=[tempPinYinHeadStr rangeOfString:input.text options:NSCaseInsensitiveSearch];
                if (titleHeadResult.length>0) {
                    //判断原来的是否存在过
                    if (_searchResultArray.count == 0 || _searchResultArray == nil) {
                        SchoolModel *model = [self.tableArray objectAtIndex:i];
                        [_searchResultArray addObject:model];
                        
                    }
                    else
                    {
                        //这个地方还是有问题 当用首字母搜索的时候 有问题！！(忽略 已经不会走这个方法了)
                        for (int j = 0; j < [_searchResultArray count]; j++) {
                            SchoolModel *result = [_searchResultArray objectAtIndex:j];
                            
                            if ([[self.schoolInfo objectForKey:myKey] isEqualToString:result.name]) {
                                continue;
                            }
                            if (j == [self.searchResultArray count] - 1) {
                                
                                SchoolModel *model = [self.tableArray objectAtIndex:i];
                                [self.searchResultArray addObject:model];
                            }
                        }
                    }
                    
                    
                }
                
            }
            //如果我的数据里都是拼音  就会走这个方法  遍历拼音  直接添加数组（想办法 直接跳到这里来，不走上面的方法 噢耶@！！！！）
            else {
                NSRange titleResult=[[self.schoolInfo objectForKey:myKey] rangeOfString:input.text options:NSCaseInsensitiveSearch];
                if (titleResult.length>0) {
                    SchoolModel *model = [self.tableArray objectAtIndex:i];
                    [_searchResultArray addObject:model];
                }
                 NSRange titleHeadResult=[[self.schoolHeadInfo objectForKey:myKey] rangeOfString:input.text options:NSCaseInsensitiveSearch];
                if (titleHeadResult.length>0) {
 
                     SchoolModel *model = [self.tableArray objectAtIndex:i];
                        [_searchResultArray addObject:model];
                        
                }
                

            }
        }//数组循环层
    }//最外层
    
    //汉字
    else if (input.text.length>0&&[ChineseInclude isIncludeChineseInString:input.text]) {
        for (SchoolModel *model in _tableArray) {
            NSRange titleResult=[model.name rangeOfString:input.text options:NSCaseInsensitiveSearch];
            if (titleResult.length>0) {
                
                [_searchResultArray addObject:model];
            }
        }
    }
    
    [self.tableView reloadData];

    
    
    
    
}


@end
